package com.leantech.android.browser.ui.favorites.vm

import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.cscj.android.repository.repo.favorites.FavoritesRepository
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.SharingStarted
import kotlinx.coroutines.flow.flatMapLatest
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.flow.stateIn
import kotlinx.coroutines.flow.update
import kotlinx.coroutines.launch
import org.koin.core.component.KoinComponent
import org.koin.core.component.inject

class FavoritesViewModel : ViewModel(), KoinComponent {

    private val favoritesRepository by inject<FavoritesRepository>()

    val favoritesEditMode: MutableStateFlow<EditMode> = MutableStateFlow(EditMode.Off)

    private val _favoritesSearchKeywordFlow = MutableStateFlow<String?>(null)

    @OptIn(ExperimentalCoroutinesApi::class)
    val favoritesFlow = _favoritesSearchKeywordFlow.flatMapLatest { keyword ->
        favoritesRepository.favorites(keyword)
    }.stateIn(
        viewModelScope,
        SharingStarted.WhileSubscribed(5000),
        emptyList()
    )

    val favoritesCountFlow = favoritesFlow.map {
        it.size
    }

    val selectedFavoritesIds = hashSetOf<Int>()

    fun getAllFavoritesId(): Set<Int> {
        return favoritesFlow.value.map {
            it.id
        }.toSet()
    }

    fun isAllSelected(): Boolean{
        return getAllFavoritesId().size == selectedFavoritesIds.size && selectedFavoritesIds.isNotEmpty()
    }

    fun toggleFavoriteEditMode() {
        favoritesEditMode.update {
            if (it == EditMode.On) {
                EditMode.Off
            } else {
                EditMode.On
            }
        }
    }

    fun deleteFavorites() {
        viewModelScope.launch {
            favoritesRepository.deleteByIds(selectedFavoritesIds.toIntArray())
        }
    }

    fun searchFavorites(keyword: String?) {
        viewModelScope.launch {
            _favoritesSearchKeywordFlow.emit(keyword)
        }
    }

    sealed interface EditMode {

        data object On : EditMode

        data object Off : EditMode

    }

}